package com.lhkk.inventoryvehicle.camera

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.SurfaceTexture
import android.hardware.Camera
import android.media.MediaScannerConnection
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.cj.mvvmlib.base.activity.BaseVmActivity
import com.cj.mvvmlib.base.viewmodel.BaseViewModel
import com.cj.mvvmlib.databinding.ActivityCameraBinding
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date


class CameraActivity : BaseVmActivity<BaseViewModel>() {
    private val TAG = "NoPreviewCamera"
    private val REQUEST_CAMERA_PERMISSION = 200

    private var mCamera: Camera? = null
    private var isCameraReleased = false
    private lateinit var cameraBinding: ActivityCameraBinding
    override fun layoutId(): View {
        cameraBinding = ActivityCameraBinding.inflate(layoutInflater)
        return cameraBinding.root
    }

    override fun initView(savedInstanceState: Bundle?) { // 检查并请求相机权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                arrayOf<String>(Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE),
                REQUEST_CAMERA_PERMISSION)
        } else { // 如果已经有权限，直接启动相机
            startCamera(1)
        }
    }

    override fun initData() {
    }

    override fun setListener() {
        cameraBinding.takePictureButton.setOnClickListener { triggerPicture() }
    }


    override fun createObserver() {
    }

    private val mPictureCallback =
        Camera.PictureCallback { data, camera -> // 在这里处理捕获到的照片数据 (byte[])
            val runnable = Runnable {
                savePicture(data)
            }
            ThreadPoolInstance.getInstance()?.getThreadPoolExecutor()?.execute(runnable)
        }

    private fun savePicture(data: ByteArray?) { // 例如，将数据保存到文件
        val pictureFile = getOutputMediaFile()
        if (pictureFile == null) {
            Log.d(TAG, "创建文件失败, 检查存储权限")
            Toast.makeText(this@CameraActivity, "保存图片失败", Toast.LENGTH_SHORT).show()
            return
        }
        try {
            val fos = FileOutputStream(pictureFile)
            fos.write(data)
            fos.close() // **新增：通知媒体扫描器扫描新文件**
            // **新增：通知媒体扫描器扫描新文件**
            MediaScannerConnection.scanFile(this@CameraActivity,
                arrayOf<String>(pictureFile.absolutePath),
                null) { path, uri ->
                Log.i(TAG, "Scanned $path:")
                Log.i(TAG, "-> uri=$uri")
            }
            Log.d(TAG, "Picture saved to " + pictureFile.absolutePath)
            Toast.makeText(this@CameraActivity, "Picture saved!", Toast.LENGTH_SHORT).show()
        } catch (e: IOException) {
            Log.e(TAG, "Error writing file: " + e.message)
            Toast.makeText(this@CameraActivity, "Error saving picture", Toast.LENGTH_SHORT).show()
        } finally { // 处理完照片后释放相机资源并关闭Activity
        }
    }

    // 启动相机并进行基本配置
    private fun startCamera(cameraId: Int) {
        if (mCamera != null && !isCameraReleased) { // 相机已经打开或已释放，不再重复打开
            return
        }
        isCameraReleased = false
        try { // 尝试打开相机
            mCamera = Camera.open(cameraId)
            if (mCamera == null) {
                Log.e(TAG, "摄像头不可用")
                finish()
                return
            }

            // 设置相机参数 (可选，但建议设置照片尺寸等)
            val params = mCamera?.parameters // 选择一个合适的照片尺寸，这里选择最大的尺寸
            var bestSize: Camera.Size? = null
            val sizes = params?.supportedPictureSizes ?: emptyList()
            for (size in sizes) {
                if (bestSize == null || size.width * size.height > bestSize.width * bestSize.height) {
                    bestSize = size
                }
            }
            if (bestSize != null) {
                params?.setPictureSize(bestSize.width, bestSize.height)
            }
            mCamera?.parameters = params // **关键步骤：设置一个虚拟的 SurfaceTexture 作为预览输出**

            // **关键步骤：设置一个虚拟的 SurfaceTexture 作为预览输出**
            val mSurfaceTexture = SurfaceTexture(10) // 参数可以是任意整数，不影响功能

            try {
                mCamera?.setPreviewTexture(mSurfaceTexture)
            } catch (e: IOException) {
                Log.e(TAG, "设置预览异常: " + e.message)
            }

            // **关键步骤：启动预览**
            // 即使不显示预览，也需要启动预览来让相机准备好拍照
            mCamera?.startPreview();
            Log.d(TAG, "Camera started successfully")
        } catch (e: java.lang.Exception) {
            Log.e(TAG,
                "Error accessing camera: " + e.message) //            releaseCamera() // 发生错误时释放相机
            //            finish()
        }
    }

    // 触发拍照
    private fun triggerPicture() {
        if (mCamera != null) {
            Log.d(TAG, "Taking picture...") // 调用 takePicture，前两个参数为 null 表示不需要原始数据和快门声音/;
            mCamera?.takePicture(null, null, mPictureCallback)
        } else {
            Log.d(TAG, "相机不可用，无法执行拍照")
        }
    }

    /** Create a File for saving an image  */
    private fun getOutputMediaFile(): File? { // 获取外部存储的公共图片目录
        val mediaStorageDir =
            File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "NoPreviewCamera")

        // 如果目录不存在，创建目录
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(TAG, "failed to create directory")
                return null
            }
        }

        // 创建媒体文件名
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        return File(mediaStorageDir.path + File.separator + "IMG_" + timeStamp + ".jpg")
    }

    // 释放相机资源
    private fun releaseCamera() {
        if (mCamera != null && !isCameraReleased) {
            mCamera?.release() // 释放相机资源
            mCamera = null
            isCameraReleased = true
            Log.d(TAG, "Camera released")
        }

        // 释放 SurfaceTexture
        //        if (mSurfaceTexture != null) {
        //            mSurfaceTexture.release()
        //            mSurfaceTexture = null
        //            Log.d(TAG, "SurfaceTexture released")
        //        }
    }

    // 你可以添加一个方法来切换摄像头
    fun switchCamera(cameraId: Int) {
        if (mCamera != null) {
            releaseCamera() // 释放当前相机和 SurfaceTexture
            startCamera(cameraId) // 启动新ID的相机
        }
    }
}
